#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import request, render_template, flash, redirect, url_for, Blueprint, g
from my_app import db, login_manager
from flask_login import current_user, login_user, logout_user, login_required
from my_app.auth.models import User, RegistrationForm, LoginForm

auth = Blueprint('auth', __name__)


@auth.route('/')
@auth.route('/home')
def home():
    return render_template('home.html', username=request.form.get('username'))


@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))


@auth.before_request
def get_current_user():
    g.user = current_user


@auth.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:  # 检查是否已经登录
        flash('您已经登录，请退出后再进行注册。', 'info')
        return redirect(url_for('auth.home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        username = request.form.get('username')
        password = request.form.get('password')
        existing_username = User.query.filter_by(username=username).first()
        if existing_username:
            flash('此用户名已被占用，请尝试另一个。', 'warning')
            return render_template('users/register.html', form=form)
        user = User(username, password)
        db.session.add(user)
        db.session.commit()
        flash(f'{username} 您已注册成功，请登录。', 'success')
        return redirect(url_for('auth.login'))
    if form.errors:
        flash(form.errors, 'danger')
    return render_template('users/register.html', form=form)


@auth.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:  # 检查是否已经登录
        flash('您已经登录，请退出后再进行登录。', 'info')
        return redirect(url_for('auth.home'))
    form = LoginForm()
    if form.validate_on_submit():
        username = request.form.get('username')
        password = request.form.get('password')
        existing_user = User.query.filter_by(username=username).first()
        if not (existing_user and existing_user.check_password(password)):
            flash('无效的用户名或密码，请再试一次。', 'danger')
            return render_template('users/login.html', form=form)
        login_user(existing_user)
        flash('您已成功登录。', 'success')
        return redirect(url_for('auth.home'))
    if form.errors:
        flash(form.errors, 'danger')
    return render_template('users/login.html', form=form)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.home'))

